package com.uchedao.seller.ui.user;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.uchedao.seller.R;
import com.uchedao.seller.http.Api;
import com.uchedao.seller.http.HttpRequest;
import com.uchedao.seller.inf.ICityResultBack;
import com.uchedao.seller.model.CityEntity;
import com.uchedao.seller.model.ProvinceEntity;
import com.uchedao.seller.ui.baidu.BaseFragForBaidu;
import com.uchedao.seller.ui.province_city.ProvinceCityFragment;
import com.uchedao.seller.util.ImageUtils;
import com.uchedao.seller.util.LogUtil;
import com.uchedao.seller.util.UploadPicUtil;
import com.uchedao.seller.util.Util;
import com.uchedao.seller.widget.MyEditView;
import com.uchedao.seller.widget.TitleLayoutView;
import com.uchedao.seller.widget.dialog_for_ios.ActionSheetDialog;
import com.uchedao.seller.widget.dialog_for_ios.ActionSheetDialog.OnSheetItemClickListener;
import com.uchedao.seller.widget.dialog_for_ios.ActionSheetDialog.SheetItemColor;
import com.uchedao.seller.widget.dialog_for_ios.ZAlertDialog;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * 注册
 * Created by zhengxizhen on 15/10/28.
 */
public class RegisterFragment extends BaseFragForBaidu implements View.OnClickListener, ICityResultBack {

    private static BaseFragForBaidu mInstance = null;

    /**
     * 获取单例
     */
    public static synchronized BaseFragForBaidu getInstance() {
        if (mInstance == null) {
            mInstance = new RegisterFragment();
        }
        return mInstance;
    }

    public final static String IMG_CACHE_PATH = Environment
            .getExternalStorageDirectory() + "/.uchedao";

    private int GET_FROM_CAMERA = 0;
    private int GET_FROM_PHOTO = 1;

    private int photo_position = 0;

    private String path;

    private TitleLayoutView tlv_register;
    private TextView tv_city_content;
    private ImageView iv_num_photo, iv_business;
    private MyEditView mev_user_company;
    private MyEditView mev_user_name;
    private MyEditView mev_user_phone;

    private String[] photos = new String[2];
    private String company;
    private String name;
    private String phone;

    private ProvinceEntity province;
    private CityEntity city;


    @Override
    protected String getActivityTag() {
        return "RegisterFragment";
    }

    @Override
    public int getViewLayoutId() {
        return R.layout.fragment_register;
    }

    @Override
    public void initView() {
        tlv_register = (TitleLayoutView) findViewById(R.id.tlv_register);
        tv_city_content = (TextView) findViewById(R.id.tv_city_content);
        iv_num_photo = (ImageView) findViewById(R.id.iv_num_photo);
        iv_business = (ImageView) findViewById(R.id.iv_business);

        mev_user_company = (MyEditView) findViewById(R.id.mev_user_company);
        mev_user_name = (MyEditView) findViewById(R.id.mev_user_name);
        mev_user_phone = (MyEditView) findViewById(R.id.mev_user_phone);
    }

    @Override
    public void initData() {
        super.initData();
        tlv_register.setData("注册", this);
    }

    @Override
    public void initListener() {
        super.initListener();
        findViewById(R.id.btn_register).setOnClickListener(this);
        findViewById(R.id.btn_photo).setOnClickListener(this);
        findViewById(R.id.iv_business).setOnClickListener(this);
        tv_city_content.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_city_content:
                toFragment(ProvinceCityFragment.getInstance(this), true, true);
                break;
            case R.id.title_back:
                toBack(this);
                break;
            case R.id.btn_photo:
                //拍照
                showPhotoWay(0);
                break;
            case R.id.iv_business:
                //营业执照
                showPhotoWay(1);
                break;
            case R.id.btn_register:
                if (confirmData()) {
                    new ZAlertDialog.Builder(getContext())
                            .setMessage("您的审核已提交，审核通过后，我们会以短信方式通知您！")
                            .setPositiveButton(R.string.cancel, null)
                            .setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startRequest();
                                }
                            })
                            .show();
                }
                break;
        }
    }

    /**
     * 开启图片上传的异步线程
     */
    private void startRequest() {
        showProgressDialog("正在上去数据，请稍等……");
        //异步上传图片，完成后调用注册接口
        for (int i = 0; i < 2; i++) {
            upyunPhoto(i == 0 ? "id_card_photo" : "business_photo", photos[i]);
        }
    }

    /**
     * 选择图片方式
     */
    private void showPhotoWay(int position) {
        photo_position = position;
        new ActionSheetDialog(getActivity())
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("拍照", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                toCamera();
                            }
                        })
                .addSheetItem("相册", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                toPhoto();
                            }
                        })
                .show();
    }

    /**
     * 验证数据
     */
    private boolean confirmData() {
        company = mev_user_company.getString();
        if (TextUtils.isEmpty(company)) {
            return false;
        }
        if (province == null
                || city == null) {
            showToast("请选择所在城市！");
            return false;
        }
        phone = mev_user_phone.getString();
        if (TextUtils.isEmpty(phone)) {
            return false;
        }
        name = mev_user_name.getString();
        if (TextUtils.isEmpty(name)) {
            return false;
        }
        if (TextUtils.isEmpty(photos[0])) {
            showToast("人证合照不能为空！");
            return false;
        }
        if (TextUtils.isEmpty(photos[1])) {
            showToast("营业执照不能为空！");
            return false;
        }
        return true;
    }

    /**
     * 提交注册，后台审核
     */
    private void requestRegister() {
        if (result_total < 2) {
            return;
        }
        if (TextUtils.isEmpty(id_card_photo)
                || TextUtils.isEmpty(business_photo)) {
            cancelProgressDialog();
            new ZAlertDialog.Builder(getActivity())
                    .setMessage("图片上传失败，是否重新上传？")
                    .setPositiveButton(R.string.cancel, null)
                    .setNegativeButton("重新上传", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startRequest();
                        }
                    }).show();
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("province", province.getId() + "");
        map.put("city", city.getId() + "");
        map.put("name", name);
        map.put("mobile", phone);
        map.put("id_card_photo", id_card_photo);
        map.put("business_photo", business_photo);
        map.put("app_name", "sale");
        map.put("registration_id", JPushInterface.getRegistrationID(getContext()));
        Request request = HttpRequest.getRequest(HttpRequest.POST, Api.Action.USER_REGISTER, map
                , new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                cancelProgressDialog();
                //提交成功回到登录页面
                toBack(mInstance);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                cancelProgressDialog();
                Toast.makeText(getContext(), error.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });
        addQueue(request);
    }


    /**
     * 照相机
     */
    private void toCamera() {
        if (!Util.existSDCard()) {
            showToast("存储卡不可用，暂无法完成拍照!");
            return;
        }

        path = IMG_CACHE_PATH + "/" + System.currentTimeMillis() + ".png";

        File vFile = new File(path);

        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        }
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vFile));
        startActivityForResult(cameraIntent, GET_FROM_CAMERA);
    }

    /**
     * 相册
     */
    private void toPhoto() {
        if (!Util.existSDCard()) {
            showToast("存储卡不可用，暂无法从相册提取相片!");
            return;
        }
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, null);
        galleryIntent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(galleryIntent, GET_FROM_PHOTO);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == GET_FROM_CAMERA) {
            savePath(path);
//            File tempFile = new File(path);
//            startPhotoZoom(Uri.fromFile(tempFile));
        } else if (requestCode == GET_FROM_PHOTO) {
            savePath(getAbsoluteImagePath(data.getData()));
//            startPhotoZoom(data.getData());
        }
    }

    /**
     * 存储图片路径
     */
    private void savePath(String path) {
        if (TextUtils.isEmpty(path)) {
            showToast("图片路径错误！");
        } else {
            photos[photo_position] = path;
            if (photo_position == 0) {
                ImageUtils.loadImage(Util.getSDcardImageUrl(path), iv_num_photo);
            } else {
                ImageUtils.loadImage(Util.getSDcardImageUrl(path), iv_business);
            }
        }
    }

    /**
     * Ur转换真实路径
     */
    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().managedQuery(uri,
                proj,                 // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);                 // Order-by clause (ascending by name)

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    @Override
    public void onCityResult(ProvinceEntity province, CityEntity city) {
        LogUtil.e("onCityResult");
        if (TextUtils.isEmpty(province.getName())
                || TextUtils.isEmpty(city.getName())) {
            return;
        }
        this.province = province;
        this.city = city;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (province != null && city != null) {
            handler.sendEmptyMessage(0);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String string = String.format("%s", city.getName());
            tv_city_content.setText(string);
        }
    };


    private UploadPicUtil upUtil;
    private int result_total = 0;
    private String id_card_photo, business_photo;

    public void upyunPhoto(String moduleName, String filePath) {
        if (upUtil == null) {
            upUtil = new UploadPicUtil(getActivity());
        }
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                if (isSucceed) {
                    if (moduleName.equals("id_card_photo")) {
                        id_card_photo = result;
                    } else if (moduleName.equals("business_photo")) {
                        business_photo = result;
                    }
                } else {
                    if (moduleName.equals("id_card_photo")) {
                        id_card_photo = null;
                    } else if (moduleName.equals("business_photo")) {
                        business_photo = null;
                    }
                }
                result_total++;
                requestRegister();
            }
        };
        upUtil.upSinglePic(moduleName, filePath, callback);
    }
}
